/*
 * Copyright (c) 2020 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * introduction:
 * Mrobot UnionDevices V2 版本  
 * mq2传感器驱动程序
 */

#ifndef __TOUCH_SENSOR__
#define __TOUCH_SENSOR__

#define IOT_FAILURE 1
#define IOT_SUCCESS 0

#define TOUCH_ADC6 13 // sensor
void SensorInit(void);
void MQ2_PPM_Calibration(void);
float Get_MQ2_PPM(void);
float GetVoltage(void);

#define AHT20_SCL 1
#define AHT20_SDA 0
#define AHT20_I2C_IDX 1               // --i2c1
#define AHT20_I2C_BAUDRATE 400 * 1000 // --i2c波特率400K
#define AHT20_ADDR 0x38
#define AHT20_READ ((0x38 << 1) | 0x1)  // --SDA-读
#define AHT20_WRITE ((0x38 << 1) | 0x0) // --SDA-写
#define AHT20_INIT_CMD 0xBE             // --初始化(校准)命令
#define AHT20_INIT_CMD_B1 0x08
#define AHT20_INIT_CMD_B2 0x00
#define AHT20_TRAG_CMD 0xAC // --触发测量
#define AHT20_TRAG_CMD_B1 0x33
#define AHT20_TRAG_CMD_B2 0
#define AHT20_RESET_CMD 0xBA // --软复位（不断电复位）
#define AHT20_STATUS 0x71    // --获取状态位
#define AHT20_WAIT_TIME 100  // 复位、传感器测量数据等待时间 ms

/**
 * STATUS 命令回复：
 * 1. 初始化后触发测量之前，STATUS 只回复 1B 状态值；
 * 2. 触发测量之后，STATUS 回复6B： 1B 状态值 + 2B 湿度 + 4b湿度 + 4b温度 + 2B 温度
 *      RH = Srh / 2^20 * 100%
 *      T  = St  / 2^20 * 200 - 50
 **/
#define AHT20_STATUS_BUSY_SHIFT 7 // bit[7] Busy indication
#define AHT20_STATUS_BUSY_MASK (0x1 << AHT20_STATUS_BUSY_SHIFT)
#define AHT20_STATUS_BUSY(status) ((status & AHT20_STATUS_BUSY_MASK) >> AHT20_STATUS_BUSY_SHIFT)

#define AHT20_STATUS_MODE_SHIFT 5 // bit[6:5] Mode Status
#define AHT20_STATUS_MODE_MASK (0x3 << AHT20_STATUS_MODE_SHIFT)
#define AHT20_STATUS_MODE(status) ((status & AHT20_STATUS_MODE_MASK) >> AHT20_STATUS_MODE_SHIFT)

// bit[4] Reserved
#define AHT20_STATUS_CALI_SHIFT 3 // bit[3] CAL Enable
#define AHT20_STATUS_CALI_MASK (0x1 << AHT20_STATUS_CALI_SHIFT)
#define AHT20_STATUS_CALI(status) ((status & AHT20_STATUS_CALI_MASK) >> AHT20_STATUS_CALI_SHIFT)
// bit[2:0] Reserved

#define AHT20_STATUS_RESPONSE_MAX 6

#define AHT20_RESLUTION (1 << 20) // 2^20

#define AHT20_MAX_RETRY 10

void AHT20_I2C_Init(void);

unsigned int AHT20_Calibrate(void);

unsigned int AHT20_StartMeasure(void);

unsigned int AHT20_GetMeasureResult(float *temp, float *humi);

#endif